import React, { useMemo, useRef } from 'react';
import { v4 as uuid } from 'uuid';
import { IChatDialogueMessageSchema } from '@/types/chat';
import { useAppSelector } from '@/store';
import { cloneDeep } from 'lodash';
import ChatContent from './ChatContent';

const ChatCompletion: React.FC = () => {
  const { history, currentDialog } = useAppSelector((state) => state.chat);
  const scrollableRef = useRef<HTMLDivElement>(null);

  const showMessages = useMemo(() => {
    const tempMessage: IChatDialogueMessageSchema[] = cloneDeep(history);
    return tempMessage
      .filter((item) => ['ai', 'human'].includes(item.role))
      .map((item) => {
        return {
          ...item,
          key: uuid(),
        };
      });
  }, [history]);

  // useEffect(() => {
  //   setTimeout(() => {
  //     console.log('@@history[history.length - 1]?.context', history[history.length - 1]?.context);
  //     scrollableRef.current?.scrollTo(0, scrollableRef.current?.scrollHeight);
  //   }, 50);
  // }, [history, history[history.length - 1]?.context]);
  return (
    <div className="flex flex-col w-5/6 mx-auto" ref={scrollableRef}>
      {!!showMessages.length &&
        showMessages.map((content, index) => {
          return <ChatContent key={index} content={content} />;
        })}
      {currentDialog ? <ChatContent key={history.length} content={currentDialog} /> : ''}
    </div>
  );
};

export default ChatCompletion;
